/*
 *
 *    BLITZ Google Analytics for iPhone
 *    Copyright (C) 2009 BLITZ Digital Studios LLC d/b/a BLITZ Agency.
 *
 *    This library is free software; you can redistribute it and/or modify it 
 *    under the terms of the GNU Lesser General Public License as published
 *    by the Free Software Foundation; either version 2.1 of the License, or 
 *    (at your option) any later version.
 *
 *    This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 *    without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
 *    PURPOSE. See the GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License along 
 *    with this library; if not, write to the Free Software Foundation, Inc.,
 *    59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 *
 *    BLTIZ Digital Studios LLC, 3415 S. Sepulveda BLVD, Ste 500, Los Angeles CA, 90034
 *    http://www.blitzagency.com
 *    http://labs.blitzagency.com
 *
 *        Author: Adam Venturella - aventurella@blitzagency.com
 *
 */

#import "BLITZTracking.h"
#import "GoogleAnalytics.h"
#import <sqlite3.h>

#define kAnalyticsFile     @"analytics.sql"
#define kBLITZPath         @"BLITZAnalytics"

@interface BLITZTracking(Private)
-(void)initializeOfflineStorage;
-(void)createOfflineStorage;
-(void)activateOfflineStorageWithPath:(NSString *)path;
-(BOOL)needsSynchronize;
@end

@implementation BLITZTracking

-(void)dealloc
{
	[analytics release];
	sqlite3_close(database);
	[super dealloc];
}

-(id)initWithGAAccount:(NSString *)account andHost:(NSString *)host
{
	if(self = [super init])
	{
		analytics = [[GoogleAnalytics alloc] initWithAccount:account andHost:host];
		[self initializeOfflineStorage];
		
		if([self needsSynchronize]){
			[analytics synchronize];
		}
	}
	
	return self;		
}

-(void)track:(NSString *)value
{
	[analytics track:value];
}

-(BOOL)needsSynchronize
{
	BOOL result = NO;
	const char *sql = "SELECT COUNT(*) FROM analyticsobject";
	sqlite3_stmt *statement;
	
	if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) 
	{
		sqlite3_step(statement);
		int count  = sqlite3_column_int(statement, 0);
		
		if(count > 0){
			result = YES;
		}
	}
	
	sqlite3_finalize(statement);
	
	return result;
}

-(void)initializeOfflineStorage
{
    BOOL success;
	NSString *dbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    dbPath           = [dbPath stringByAppendingPathComponent:kBLITZPath];
	dbPath           = [dbPath stringByAppendingPathComponent:kAnalyticsFile];
    success          = [[NSFileManager defaultManager] fileExistsAtPath:dbPath];
   
	if (success)
	{
		[self activateOfflineStorageWithPath:dbPath];
	}
	else
	{
		[self createOfflineStorage];
	}
	
}
	
-(void)createOfflineStorage
{
	BOOL       success;
	NSError  * error;
	NSString * path      = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	path                 = [path stringByAppendingPathComponent:kBLITZPath];
	
	if(![[NSFileManager defaultManager] fileExistsAtPath:path]){
		[[NSFileManager defaultManager] createDirectoryAtPath:path attributes:nil];
	}
	
	path = [path stringByAppendingPathComponent:kAnalyticsFile];
	
	NSString * defaultdb  = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kAnalyticsFile];
	success = [[NSFileManager defaultManager] copyItemAtPath:defaultdb toPath:path error:&error];
	
	if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
	
	[self activateOfflineStorageWithPath:path];
}

-(void)activateOfflineStorageWithPath:(NSString *)path
{	
	if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) 
	{
		[analytics setOfflineSQLStore:database];
	}
	else
	{
		 NSAssert1(0, @"%@", @"Failed to initilize database");
	}
}

@end
